import { getAllStyleByDsno } from '../../../../mapUtils/StyleListUtil';
import { getStyle, formatDeviceFeature } from '../../../../mapUtils/StyleListUtil';
import { parse } from '../../../../mapUtils/Geojson2WktUtil';
import { projectLngLatToWebMercator } from '../../../../mapUtils/CoordinateUtil';
import IGridTool from '../IGridTool';
import Layer from '../../constant/Layer';
import Prefix from '../../constant/Prefix';

/**
 * 电缆廊道图层工具箱
 * @implements {IGridTool}
 */
class CableGridTool extends IGridTool {
  constructor(_top, _impl) {
    super(_top, _impl);
    this.name = 'CableGridTool';
    this.desc = '电缆廊道图层工具箱';
    this.layeridPrefix = Prefix['CableGrid'];
    this.defaultSchemaid = 9;
    this.defaultSysDsno = 7;
    this.searchArea = '';
    this._refresh = this.refresh.bind(this);
  }

  /**
   * 初始化电缆廊道图层
   * @override
   */
  createCustomLayer() {
    // 初始化数据源
    this._CableSourceId = this.layeridPrefix + '_source_Cable_' + this.id;
    if(!this.getMap().getSource(this._CableSourceId)) {
      this.getMap().addSource(this._CableSourceId, {
        type: 'geojson',
        data: {
          type: 'FeatureCollection',
          features: []
        }
      });
    }
    // 初始化图层
    // 创建现状廊道图层
    let styles = getAllStyleByDsno(this.defaultSysDsno);
    styles.lineStyle.forEach((style) => {
      // 创建线图层
      let id = `${this.layeridPrefix}_gridstyle_layer_${style.type}_${style.sbzlx}`;
      this._layerIds.push(id);
      this._layerIdsAll.push(id);
      let lineLayerOpts = {
        id: id,
        type: 'line',
        source: this._CableSourceId,
        filter: ['all', ['==', 'transSbzlx', style.sbzlx * 1]],
        paint: {
          'line-color': ['get', 'color'],
          'line-width': ['get', 'width']
        }
      };
      if (style.sbzlx * 1 === 891000000) {
        lineLayerOpts.paint['line-dasharray'] = [1, 1];
      }
      if(!this.getMap().getLayer(id)) {
        this.getMap().addLayer(lineLayerOpts);
      }
      // 创建线标注图层
      let labelLayerid = `${this.layeridPrefix}_gridstyle_layer_${style.type}_${style.sbzlx}_label`;
      this._layerIdsAll.push(labelLayerid);
      if(!this.getMap().getLayer(labelLayerid)) {
        this.getMap().addLayer({
          id: labelLayerid,
          type: 'symbol',
          source: this._CableSourceId,
          filter: ['all', ['==', 'transSbzlx', style.sbzlx * 1]],
          layout: {
            'symbol-placement': 'line',
            'icon-ignore-placement': true,
            'icon-anchor': 'center',
            'text-field': '{' + Layer.GlobalMarkLabelField + '}',
            'text-size': 12,
            'text-font': ['Microsoft YaHei Regular'],
            'text-offset': [0, 0],
            'text-max-width': 8,
            'text-allow-overlap': false,
            'text-ignore-placement': false
          },
          paint: {
            'text-color': ['get', 'color'],
            'text-halo-color': '#FFFFFF',
            'text-halo-width': 1.33333
          }
        });
      }
    });
  }

  /**
   * 刷新廊道图层
   * @override
   */
  refresh() {
    if (this.isLocked()) {
      return;
    }
    // 当前请求时间
    let currentRequestTime = this.latestRequestTime = new Date().getTime();
    // 获取当前缩放等级下配置的图层列表
    this.getApi().PwghGhsjTxfw.figure.get_figure_getEquitpType({
      params: {
        zoom: this.getTool('BaseMapTool').getZoom(),
        schemaid: this.searchOption.schemaid || this.defaultSchemaid
      }
    })
      .then((data) => {
        // 过期请求不处理
        if (this._isOutDate(currentRequestTime)) {
          return;
        }
        let sbzlxs = data.datas;
        let promiselist = [];
        // 获取范围、缩放等级
        let extent = this.getTool('BaseMapTool').getBounds();
        let shape = parse(
          turf.polygon(projectLngLatToWebMercator(turf.bboxPolygon(extent).geometry.coordinates)).geometry
        );
        // 拼接请求数据
        sbzlxs.forEach((sbzlx) => {
          promiselist.push(
            new Promise((resolve) => {
              let params = Object.assign({}, this.searchOption, {
                zoom: this.getTool('BaseMapTool').getZoom(),
                sblx: sbzlx.sblx,
                shape: shape,
                oid: sbzlx.oid,
                schema: this.searchOption.schema || this.getConfig().get('SCHEMA')
              });
              this.getApi().PwghGhsjTxfw.sbjhQuery.post_sbjhQuery_showGhdwEquip({ params: params })
                .then((res) =>
                  resolve({ sblx: sbzlx.sblx, res })
                )
                .catch(() =>
                  resolve({
                    sblx: sbzlx.sblx,
                    res: {
                      datas: [],
                      // eslint-disable-next-line camelcase
                      resp_msg: '调用服务出错'
                    }
                  })
                );
            })
          );
        });
        Promise.all(promiselist).then((resList) => {
          // 过期请求不处理
          if(!this._isOutDate(currentRequestTime)) {
            this._showBySgmapLayer(resList);
          }
        });
      });
  }

  /**
   * 采用思极地图的形式绘制图层
   * @override
   * @param {Array} resList 图形数据
   * @ignore
   */
  _showBySgmapLayer(resList) {
    let gridList = [];
    let cableList = [];
    resList.forEach((res) => {
      if (res.sblx * 1 === 910000) {
        cableList.push(res);
      } else {
        gridList.push(res);
      }
    });
    // 绘制廊道图层
    this._showCableLayer(cableList);
    // 绘制电网图层
    super._showBySgmapLayer(gridList);
  }

  /**
   * 绘制电缆廊道图层
   * @param {Array} resList 图形数据
   * @ignore
   */
  _showCableLayer(resList) {
    let features = [];
    resList.forEach((res) => {
      let sblx = res.sblx;
      let datas = res.res.datas || [];
      datas.forEach((item) => {
        let shapejson = item.shapejson;
        if (shapejson) {
          item.geometry = JSON.parse(shapejson);
          item.sblx = sblx;
          item.transSbzlx = item.versionid > 0 ? Number('8' + item.sbzlx) : item.sbzlx;
          let style = getStyle(item, { zoom: this.getTool('BaseMapTool').getZoom() }, this.defaultSysDsno);
          let feature = formatDeviceFeature(item, style);
          feature.properties[Layer.GlobalMarkLabelField] = `Φ${item.dlgzj}*${item.dlgks}+Φ${item.txgzj}*${item.txgks}`;
          features.push(feature);
        } else {
          // this.info(item.sbzlx, item.oid, "设备无返回坐标信息");
        }
      });
    });
    this.getMap().getSource(this._CableSourceId).setData(turf.featureCollection(features));
  }
}

export default CableGridTool;
